package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.domain.Dish;
import com.example.domain.DishFlavor;
import com.example.dto.DishDto;
import com.example.mapper.DishMapper;
import com.example.service.DishFlavorSerivce;
import com.example.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishFlavorSerivce dishFlavorSerivce;
    @Autowired
    private DishMapper dishMapper;
    //新增菜品
    @Transactional   //多表操作需
    public void saveWithFlavor(DishDto dishDto) {
        //保存dis菜品表的信息,保存后会自动生成id
        this.save(dishDto);
        //获取菜品id
        System.out.println("service层:"+dishDto.getImage());
        Long dishid = dishDto.getId();
        //生成菜品口味集合
        List<DishFlavor> flavors=dishDto.getFlavors();
        //map想集合中添加元素，collect开始收集流
        flavors= flavors.stream().map((item)->{
            item.setDishId(dishid);
            return item;
        }).collect(Collectors.toList());

        boolean flag = dishFlavorSerivce.saveBatch(flavors);
        if(!flag){
            throw new RuntimeException("添加失败");
        }
    }
    //分页查询
    @Override
    public void getDishDtoPage(IPage<DishDto> iPage, LambdaQueryWrapper<Dish> queryWrapper) {
        dishMapper.getDishDtoPage(iPage, queryWrapper);
    }
    //修改菜品
    @Override
    @Transactional
    public void updateWithFlavor(DishDto dishDto) {
        //更新dish表基本信息
        this.updateById(dishDto);
        //清理当前dish_flavor菜品口味数据
        LambdaQueryWrapper<DishFlavor> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorSerivce.remove(queryWrapper);
        //添加当前dish_flavor菜品口味数据
        List<DishFlavor> flavors = dishDto.getFlavors();
        //map想集合中添加元素，collect开始收集流
        flavors= flavors.stream().map((item)->{
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());
        dishFlavorSerivce.saveBatch(flavors);
    }
}
